package com.pktechan.manage.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;

/**
 * @program: gsPrivateSale19
 * @description: 图片工具类
 * @author: qx.zhang
 * @create: 2020-03-26 09:53
 **/
public class ImageUtils {
    private static final Logger LOGGER = LoggerFactory.getLogger(ImageUtils.class);

    /**
     * 图片压缩尺寸算法
     *
     * @param bufferedImage 原始图片流
     * @param suffix        文件后缀名
     * @param w             目标图宽
     * @param h             目标图高
     */
    public static byte[] compressImage(BufferedImage bufferedImage, String suffix, int imageWidth, int imageHeight, int w, int h) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            // 根据原图与要求的缩略图比例，找到最合适的缩略图比例
            if (imageWidth >= imageHeight) {
                h = (int) Math.round((imageHeight * w * 1.0 / imageWidth));
            } else {
                w = (int) Math.round((imageWidth * h * 1.0 / imageHeight));
            }
            BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
            Graphics g = bi.getGraphics();
            g.drawImage(bufferedImage, 0, 0, w, h, Color.LIGHT_GRAY, null);
            g.dispose();
            // BufferedImage转byte[]
            ImageIO.write(bi, suffix, out);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("图片生成错误");
        }
        return out.toByteArray();
    }
}
